package com.elite.groovy.callback

import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
 * 企业微信推送名单接口
 * TaoHao每五分钟执行一次
 */
public  class apiQwImportResult implements  ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiQwImportResult.class);

    @Override
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        //初始化返回参数
        JSONObject result = new JSONObject();
        JdbcTemplate jt =new JdbcTemplate(eliteBean.getDataSource());
        try {
            long startTime=System.currentTimeMillis();
           String qwsql='''
                    select
                   o.objective_guid,
                   c1.customername,
                   c1.mobile,
                   c1.customer_guid,
                   o.custlistname,
                   c1.CUSTOMERTYPE_ID,
                   c1.CUSTOMERID,
                   o.map_id,
                   o.handleby_id,
                   c.CAR_PLATE,
                   c.FRAME_CODE,
                   c1.PROVINCE_ID,
                   c1.CITY_ID,
                   s.loginname
                   From objective o
                   left join customer c on o.customer_guid=c.customer_guid
                   left join customer c1 on c1.customer_guid=c.parent_guid
                   left join staff s  on o.HANDLEBY_ID=s.staff_id
                   where o.STRINGFIELD4 is not null
                   and o.STRINGFIELD4 >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                   and o.STRINGFIELD4 <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss')   
                   and c1.mobile is not null  and o.HANDLEBY_ID is not null and c.STRINGFIELD13 is null 
                   and NOT EXISTS(
                   select 
                   bb.objective_guid 
                   from qw_resultspush_temp bb
                   where  bb.OBJECTIVE_GUID=o.OBJECTIVE_GUID
                   and bb.MD_FLAG='1'
                   and bb.CREATEDDATE >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                   and bb.CREATEDDATE <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss') 
                   )  AND ROWNUM<=500
                    order by o.STRINGFIELD4 desc
                    ''';


            //电销名单
            List QwList=eliteBean.chaxun_sql(qwsql,"dataSource");
            //获取配置里key
            String secretKey = KHDBConfig.getParam(eliteBean, "QW-KEY","");//线索来源密钥
            String sourceName="电销名单";
            JSONArray  arr  =new JSONArray();
            JSONObject json2 =new JSONObject();
            JSONObject WXJSON=new JSONObject();
            JSONArray jsonArray2=JSONArray.fromObject(QwList);
            log.debug("jsonArray2"+jsonArray2);
            int ListNum2 = jsonArray2.size();
            if (QwList.size()>0){
                for (int i=0;i<ListNum2;i++){
                    JSONObject json = jsonArray2.getJSONObject(i);
                    def name=GetJV(json,"CUSTOMERNAME");                //客户名称
                    def phone=GetJV(json, "MOBILE");             //线索手机号
                    def isListCustomer="1";             // 是否名单客户 0：否；1：是
                    def listCustomerId=GetJV(json,"CUSTOMER_GUID");//名单ID
                    def batchNum=GetJV(json, "CUSTLISTNAME");//批次号
                    def businessType=GetJV(json, "MAP_ID");//业务类型
                    def idCardType=GetJV(json, "CUSTOMERTYPE_ID");//证件类型 1：身份证
                    def idCard=GetJV(json, "CUSTOMERID");//证件号
                    def handlerUserName=GetJV(json, "HANDLEBY_ID");//线索责任人
                    def handlerWwxUserId=GetJV(json, "LOGINNAME");//  线索责任人企业微信ID明文userId
                    def licenseNo=GetJV(json,"CAR_PLATE"); //车牌号 none
                    def  frameNo =GetJV(json, "FRAME_CODE");// string 否 车架号 none
                    def  socialSecurity =""; //body integer 否 是否有社保 0:没有；1:有；
                    def  promoter="";// body string 否 推广人 none
                    def  province=GetJV(json, "PROVINCE_ID");// body string 否 省份 none
                    def city=GetJV(json, "CITY_ID");// string 否 城市 none
                    def description ="";//body string 否 线索描述 长度限制255
                    def  remark="";// body string 否 备注 长度限制255
                    def objective_guid=GetJV(json,"OBJECTIVE_GUID");
                    //写入电销推送企微记录表
                    String insertSql='''
                             Insert Into 
                             qw_resultspush_temp
                             (
                             rec_guid,
                             CUSTOMERNAME,
                             MOBILE,
                             CUSTOMER_GUID,
                             CUSTLISTNAME,
                             CUSTOMERTYPE_ID,
                             CUSTOMERID,
                             MAP_ID,
                             HANDLEBY_ID,
                             CAR_PLATE,
                             FRAME_CODE,
                             PROVINCE_ID,
                             CITY_ID,
                             LOGINNAME,
                             DEAL_FLAG,
                             CREATEDDATE,
                             MD_FLAG,
                             objective_guid
                             )values(
                             Sys_Guid(),
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             '1',
                             sysdate,
                             '1',
                             ?
                             )
                             ''';
                     jt.update(insertSql,name,phone,listCustomerId,batchNum,idCardType,idCard,businessType,handlerUserName,licenseNo,frameNo,province,city,handlerWwxUserId,objective_guid);


                    json2.put("secretKey",secretKey);
                    json2.put("phone",phone);
                    json2.put("sourceName",sourceName);
                    json2.put("isListCustomer",isListCustomer);
                    json2.put("idCardType",idCardType);
                    json2.put("name",name);
                    json2.put("socialSecurity",socialSecurity);
                    json2.put("listCustomerId",listCustomerId);
                    json2.put("batchNum",batchNum);
                    json2.put("businessType",businessType);
                    json2.put("idCard",idCard);
                    json2.put("handlerWwxUserId",handlerWwxUserId);
                    json2.put("handlerUserName",handlerUserName);
                    json2.put("licenseNo",licenseNo);
                    json2.put("promoter",promoter);
                    json2.put("province",province);
                    json2.put("city",city);
                    json2.put("description",description);
                    json2.put("remark",remark);
                    json2.put("frameNo",frameNo);
                    arr.add(json2);

                }
                String obj3=arr.toString();

                WXJSON.put("clues",obj3);
                log.debug("电销发送企业微信请求JSON报文："+WXJSON.toString());
                List GetUrl = eliteBean.chaxun_sql(" select WEBSERVICEURL from sysc_interface where webtype='QW_URL' ", "dataSource");
                String URL= GetUrl.get(0).get("WEBSERVICEURL");//获取企微接口地址
                String URL2=URL.toString()+"/blue-scrm/customerclue/apiImport";
                log.debug("电销请求企业微信接口："+URL2);

                Map<String,String> headMap=new HashMap<String,String>();
                headMap.put("content-Type","application/json");
                String WSPOST= Util.doHttpPostUseHead(URL2,WXJSON.toString(),"UTF-8",5000,0,headMap);
                JSONObject BackJson=JSONObject.fromObject(WSPOST);
                log.debug("电销企业微信返回报文："+BackJson.toString());
                String code=BackJson.get("code");
                String success=BackJson.get("success");
                String data=BackJson.get("data");
                if(!code.equals("200")&&!success.equals("true")){
                    result.put("dxcode", -1);
                    result.put("dxmsg", "调用企业微信接口异常！");
                    result.put("dxbody", BackJson.toString());
                    log.debug("调用企业微信接口异常："+result.toString());
                }else{
                    result.put("dxcode", 0);
                    result.put("dxmsg", "电销请求成功！");
                    result.put("dxbody", WXJSON.toString());
                    JSONObject dataJson =JSONObject.fromObject(data);
                    JSONArray listarr=dataJson.getJSONArray("failImportClueList");
                  for(int z =0;z<listarr.size();z++) {
                      JSONObject failJson = listarr.getJSONObject(z);
                      String serialNo = GetJV(failJson, "serialNo");
                      String listCustomerId = GetJV(failJson, "listCustomerId");
                      String batchNum = GetJV(failJson, "batchNum");
                      String phone = GetJV(failJson, "phone");
                      String failCodeList = GetJV(failJson, "failCodeList");


                      String isselectsql='''
             select serialNo from qw_resultspush_temp_log where listCustomerId=?
             and CREATEDDATE >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
             and CREATEDDATE <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss')  and MD_FLAG='1'
                                    ''';


                      List<Map<String, Object>> ischaxun  = jt.queryForList(isselectsql,listCustomerId);
                      if (ischaxun.size() <= 0) {
                          //写入推送日志表
                          String fialinsert = '''   
                             Insert Into 
                             qw_resultspush_temp_log
                             (
                             rec_guid,
                             SERIALNO,
                             LISTCUSTOMERID,
                             BATCHNUM,
                             PHONE,
                             FAILCODELIST,
                             CREATEDDATE,
                             MD_FLAG
                             )values(
                             Sys_Guid(),
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             sysdate,
                             '1'
                             )
                                      ''';

                          jt.update(fialinsert, serialNo, listCustomerId, batchNum, phone, failCodeList);

                          //删除推送表
                          String faildel = ''' 
                                    DELETE FROM qw_resultspush_temp  WHERE CUSTOMER_GUID=? AND MD_FLAG='1'
                                    ''';
                          jt.update(faildel, listCustomerId);
                      }else{

                          //更新推送日志表
                          String fialupdate= '''   
                             Update 
                             qw_resultspush_temp_log
                             set
                             SERIALNO=?,
                             BATCHNUM=?,
                             PHONE=?,
                             FAILCODELIST=?,
                             CREATEDDATE=sysdate
                             where listCustomerId=?
                             and CREATEDDATE >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                             and CREATEDDATE <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss')  
                             and MD_FLAG='1'
                                      ''';

                          jt.update(fialupdate, serialNo, batchNum, phone, failCodeList,listCustomerId);

                          //删除推送表
                          String faildel = ''' 
                                    DELETE FROM qw_resultspush_temp  WHERE CUSTOMER_GUID=? AND MD_FLAG='1'
                                    ''';
                          jt.update(faildel, listCustomerId);



                      }


                  }


                    log.debug("电销请求成功调用企业微信："+result.toString());
                }




            }else{
                log.error("电销没有数据可以推送给企微");
                result.put("dxcode", -1);
                result.put("dxmsg", "电销没有数据可以推送给企微");
                log.debug("电销没有数据可以推送给企微："+result.toString());

            }


            log.debug("-------------------------开始执行网销名单--------------------------------");




            String wxsql=''' 
          select x.TB_NAME,x.mobile,o.customer_guid,o.custlistname,x.TB_ZJH,o.map_id,o.handleby_id,s.loginname,o.objective_guid
                   From objective o
                   left join xbgl_batch_list x on x.rec_guid=o.objective_guid
                   left join staff s  on o.HANDLEBY_ID=s.staff_id
                   left join customer c on c.customer_guid=o.customer_guid 
                   where o.STRINGFIELD4 is not null
                   and o.STRINGFIELD4 >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                   and o.STRINGFIELD4 <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss')   
                   and x.mobile is not null  
                   and o.HANDLEBY_ID is not null 
                   and c.STRINGFIELD13='网销'
                   and NOT EXISTS(
                   select 
                   bb.objective_guid 
                   from qw_resultspush_temp bb
                   where  bb.OBJECTIVE_GUID=o.OBJECTIVE_GUID
                   and bb.MD_FLAG='2'
                   and bb.CREATEDDATE >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                   and bb.CREATEDDATE <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss') 
                   )
                   AND ROWNUM<=500
                 order by o.STRINGFIELD4 desc
                         ''';


            //网销名单
            List WXList=eliteBean.chaxun_sql(wxsql,"dataSource");
            //获取配置里key
            String wxsecretKey = KHDBConfig.getParam(eliteBean, "WX-KEY","");//线索来源密钥
            String wxsourceName="网销名单";
            JSONArray  arr2  =new JSONArray();
            JSONObject json3 =new JSONObject();
            JSONObject result1 =new JSONObject();
            JSONArray jsonArray3=JSONArray.fromObject(WXList);
            JSONObject WSJSON=new JSONObject();
            log.debug("jsonArray3"+jsonArray3);
            int ListNum3 = jsonArray3.size();
            if (WXList.size()>0){
                for (int i=0;i<ListNum3;i++){
                    JSONObject json = jsonArray3.getJSONObject(i);
                    def name=GetJV(json,"TB_NAME");                //客户名称
                    def phone=GetJV(json, "MOBILE");             //线索手机号
                    def isListCustomer="1";             // 是否名单客户 0：否；1：是
                    def listCustomerId=GetJV(json,"CUSTOMER_GUID");//名单ID
                    def batchNum=GetJV(json, "CUSTLISTNAME");//批次号
                    def businessType=GetJV(json, "MAP_ID");//业务类型
                    def idCardType="1";//证件类型 1：身份证`
                    def idCard=GetJV(json, "TB_ZJH");//证件号
                    def handlerUserName=GetJV(json, "HANDLEBY_ID");//线索责任人
                    def handlerWwxUserId=GetJV(json, "LOGINNAME");//  线索责任人企业微信ID明文userId
                    def licenseNo=""; //车牌号 none
                    def  frameNo ="";// string 否 车架号 none
                    def  socialSecurity =""; //body integer 否 是否有社保 0:没有；1:有；
                    def  promoter="";// body string 否 推广人 none
                    def  province="";// body string 否 省份 none
                    def city="";// string 否 城市 none
                    def description ="";//body string 否 线索描述 长度限制255
                    def  remark="";// body string 否 备注 长度限制255
                    def objective_guid=GetJV(json,"OBJECTIVE_GUID");

                    /**
                     * 插入临时表--网销
                     */
                    String insertSql2='''
                             Insert Into 
                             qw_resultspush_temp
                             (
                             rec_guid,
                             CUSTOMERNAME,
                             MOBILE,
                             CUSTOMER_GUID,
                             CUSTLISTNAME,
                             CUSTOMERID,
                             MAP_ID,
                             HANDLEBY_ID,
                             LOGINNAME,
                             DEAL_FLAG,
                             CREATEDDATE,
                             MD_FLAG,
                             objective_guid
                             )values(
                             sys_guid(),
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             '1',
                             sysdate,
                             '2',
                             ?  
                             )
           
                            ''';

                    jt.update(insertSql2,name,phone,listCustomerId,batchNum,idCard,businessType,handlerUserName,handlerWwxUserId,objective_guid);

                    json3.put("secretKey",wxsecretKey);
                    json3.put("phone",phone);
                    json3.put("sourceName",wxsourceName);
                    json3.put("isListCustomer",isListCustomer);
                    json3.put("idCardType",idCardType);
                    json3.put("name",name);
                    json3.put("socialSecurity",socialSecurity);
                    json3.put("listCustomerId",listCustomerId);
                    json3.put("batchNum",batchNum);
                    json3.put("businessType",businessType);
                    json3.put("idCard",idCard);
                    json3.put("handlerWwxUserId",handlerWwxUserId);
                    json3.put("handlerUserName",handlerUserName);
                    json3.put("licenseNo",licenseNo);
                    json3.put("promoter",promoter);
                    json3.put("province",province);
                    json3.put("city",city);
                    json3.put("description",description);
                    json3.put("remark",remark);
                    json3.put("frameNo",frameNo);
                    arr2.add(json3);

                }
                String obj3=arr2.toString();

                WSJSON.put("clues",obj3);
                log.debug("网销名单发送企业微信请求JSON报文："+WSJSON.toString());
                List GetUrl = eliteBean.chaxun_sql(" select WEBSERVICEURL from sysc_interface where webtype='QW_URL' ", "dataSource");
                String URL= GetUrl.get(0).get("WEBSERVICEURL");//获取企微接口地址
                String URL2=URL.toString()+"/blue-scrm/customerclue/apiImport";
                log.debug("网销名单请求企业微信接口："+URL2);

                Map<String,String> headMap=new HashMap<String,String>();
                headMap.put("content-Type","application/json");
                String WSPOST= Util.doHttpPostUseHead(URL2,WSJSON.toString(),"UTF-8",5000,0,headMap);
                JSONObject BackJson=JSONObject.fromObject(WSPOST);
                log.debug("网销名单企业微信接口返回报文："+BackJson.toString());
                String code=BackJson.get("code");
                String success=BackJson.get("success");
                String data=BackJson.get("data");
                if(!code.equals("200")&&!success.equals("true")){
                    result1.put("wxcode", -1);
                    result1.put("wxmsg", "调用企业微信接口异常！");
                    result1.put("wxbody", BackJson.toString());

                    log.debug("调用企业微信接口异常："+result1.toString());

                }else{
                    result1.put("wxcode", 0);
                    result1.put("wxmsg", "请求成功！");
                    result1.put("wxbody", WSJSON.toString());
                    log.debug("调用企业处理成功："+result1.toString());
                        JSONObject dataJson =JSONObject.fromObject(data);
                    JSONArray listarr=dataJson.getJSONArray("failImportClueList");

                    for(int z =0;z<listarr.size();z++){
                        JSONObject failJson = listarr.getJSONObject(z);
                        String serialNo=GetJV(failJson,"serialNo");
                        String listCustomerId=GetJV(failJson,"listCustomerId");
                        String batchNum =GetJV(failJson,"batchNum");
                        String  phone=GetJV(failJson,"phone");
                        String  failCodeList =GetJV(failJson,"failCodeList");


                        String isselectsql='''
             select serialNo from qw_resultspush_temp_log where listCustomerId=?
             and CREATEDDATE >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
             and CREATEDDATE <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss')
               and MD_FLAG='2'
                                    ''';


                        List<Map<String, Object>> ischaxun  = jt.queryForList(isselectsql,listCustomerId);

                        if (ischaxun.size()<=0){
                        //写入推送日志表
                        String fialinsert ='''   
                             Insert Into 
                             qw_resultspush_temp_log
                             (
                             rec_guid,
                             SERIALNO,
                             LISTCUSTOMERID,
                             BATCHNUM,
                             PHONE,
                             FAILCODELIST,
                             CREATEDDATE,
                             MD_FLAG
                             )values(
                             Sys_Guid(),
                             ?,
                             ?,
                             ?,
                             ?,
                             ?,
                             sysdate,
                             '2'
                             )
                                      ''';

                        jt.update(fialinsert,serialNo,listCustomerId,batchNum,phone,failCodeList);

                        //删除推送表
                        String faildel=''' 
                                    DELETE FROM qw_resultspush_temp  WHERE CUSTOMER_GUID=? AND MD_FLAG='2'
                                    ''';

                        jt.update(faildel,listCustomerId);

                        }else{

                            //更新推送日志表
                            String fialupdate= '''   
                             Update 
                             qw_resultspush_temp_log
                             set
                             SERIALNO=?,
                             BATCHNUM=?,
                             PHONE=?,
                             FAILCODELIST=?,
                             CREATEDDATE=sysdate
                             where listCustomerId=?
                             and CREATEDDATE >=to_date(to_char(sysdate,'YYYY-MM-DD')||'00:00:00','yyyy-mm-dd hh24:mi:ss')
                             and CREATEDDATE <=to_date(to_char(sysdate,'YYYY-MM-DD')||'23:59:59','yyyy-mm-dd hh24:mi:ss')  
                             and MD_FLAG='2'
                                      ''';

                            jt.update(fialupdate, serialNo, batchNum, phone, failCodeList,listCustomerId);

                            //删除推送表
                            String faildel = ''' 
                                    DELETE FROM qw_resultspush_temp  WHERE CUSTOMER_GUID=? AND MD_FLAG='2'
                                    ''';
                            jt.update(faildel, listCustomerId);



                        }
                    }

                }

            }else{
                log.error("网销没有数据可以推送给企微");
                result1.put("wxcode", -1);
                result1.put("wxmsg", "网销没有数据可以推送给企微");
                log.debug("网销没有数据可以推送给企微："+result1.toString());
            }


            long endTime=System.currentTimeMillis();
       log.debug("企微接口推送处理完成调用处理时长(毫秒):" + (endTime - startTime));
        }catch (Exception e) {
            log.error("调用企业微信接口异常：", e);
        }
    }
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }


}
